package com.cbd.log;

import cn.dev33.satoken.stp.StpUtil;
import com.cbd.entity.OpLogEntity;
import com.cbd.rabbitmq.MyMQProducer;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author BingBing
 * @desc 日志切面类
 * @date 2024/11/25 10:14
 */
@Component
@Aspect
@Slf4j
public class LogAspect {
    @Resource
    MyMQProducer myMQProducer;

    // 定义切点
    @After("@annotation(com.cbd.log.OpLog)")  // 注解切点
    public void log(JoinPoint joinPoint) {
        String username = StpUtil.getLoginIdAsString();
        log.info("登录用户：{}", username);
        Object target = joinPoint.getTarget();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();  // 获取方法对象
        OpLog opLog = method.getAnnotation(OpLog.class);  // 获取注解对象
        String type = opLog.type();  // 获取注解属性值(类型)
        String info = opLog.info();  // 获取注解属性值(信息)
        // 记录日志时间戳
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        String time = now.format(formatter);
        OpLogEntity opLogEntity = new OpLogEntity(null, username, info, time);
        // 记录日志
        myMQProducer.send(opLogEntity);
    }

    @Before("@annotation(com.cbd.log.LogOut)")
    public void before(JoinPoint joinPoint) {
        String username = StpUtil.getLoginIdAsString();
        log.info("登录用户：{}", username);
        Object target = joinPoint.getTarget();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();  // 获取方法对象
        LogOut opLog = method.getAnnotation(LogOut.class);  // 获取注解对象
        String type = opLog.type();  // 获取注解属性值(类型)
        String info = opLog.info();  // 获取注解属性值(信息)
        // 记录日志时间戳
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime now = LocalDateTime.now();
        String time = now.format(formatter);
        OpLogEntity opLogEntity = new OpLogEntity(null, username, info, time);
        // 记录日志
        myMQProducer.send(opLogEntity);
    }
}
